/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package threading_webserver;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.*;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
import org.xml.sax.*;

/**
 * @author Koen
 */
public class Settings {

    public static int webPort = 8080;
    public static int controlPort = 8081;
    public static String webRoot = System.getProperty("user.dir") + "\\";// "D:\\web-server-2014\\Threading_Webserver";
    public static String[] defaultPages = new String[]{"index.html", "login.html"};

    public static void setSettingsFromXML() {
        Document dom;
        // Make an  instance of the DocumentBuilderFactory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // use the factory to take an instance of the document builder
            DocumentBuilder db = dbf.newDocumentBuilder();
            // parse using the builder to get the DOM mapping of the    
            // XML file
            File f = new File(webRoot + "\\settings.xml");
            
            if(!f.exists())
                Save();

            dom = db.parse(f);

            Element doc = dom.getDocumentElement();

            webPort = getIntValue(webPort, doc, "webport");
            controlPort = getIntValue(controlPort, doc, "controlport");
            webRoot = getTextValue(webRoot, doc, "webroot");
            defaultPages[0] = getTextValue(defaultPages[0], doc, "defaultpage");

        } catch (ParserConfigurationException pce) {
            System.out.println(pce.getMessage());
        } catch (SAXException se) {
            System.out.println(se.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
    }

    private static int getIntValue(int def, Element doc, String tag) {
        String value = "" + def;
        NodeList nl;
        nl = doc.getElementsByTagName(tag);
        if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
            value = nl.item(0).getFirstChild().getNodeValue();
        }
        return Integer.parseInt(value);
    }

    private static String getTextValue(String def, Element doc, String tag) {
        String value = def;
        NodeList nl;
        nl = doc.getElementsByTagName(tag);
        if (nl.getLength() > 0 && nl.item(0).hasChildNodes()) {
            value = nl.item(0).getFirstChild().getNodeValue();
        }
        return value;
    }

    public static void Save() {
        File f = new File(webRoot + "\\settings.xml");
        Document dom;
        Element e = null;

        // instance of a DocumentBuilderFactory
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            // use factory to get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();
            // create instance of DOM
            dom = db.newDocument();

            // create the root element
            Element rootEle = dom.createElement("settings");

            // create data elements and place them under root
            e = dom.createElement("webport");
            e.appendChild(dom.createTextNode(webPort + ""));
            rootEle.appendChild(e);

            e = dom.createElement("controlport");
            e.appendChild(dom.createTextNode(controlPort + ""));
            rootEle.appendChild(e);

            e = dom.createElement("webroot");
            e.appendChild(dom.createTextNode(webRoot));
            rootEle.appendChild(e);

            e = dom.createElement("defaultpage");
            e.appendChild(dom.createTextNode(defaultPages[0]));
            rootEle.appendChild(e);

            dom.appendChild(rootEle);

            try {
                Transformer tr = TransformerFactory.newInstance().newTransformer();
                tr.setOutputProperty(OutputKeys.INDENT, "yes");
                tr.setOutputProperty(OutputKeys.METHOD, "xml");
                tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

                // send DOM to file
                tr.transform(new DOMSource(dom),
                        new StreamResult(new FileOutputStream(f)));

            } catch (TransformerException te) {
                System.out.println(te.getMessage());
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ParserConfigurationException pce) {
            System.out.println("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
        }
    }
}
